package com.bawei.yuekao.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.bawei.yuekao.R;
import com.bawei.yuekao.adapter.SongAdapter;
import com.bawei.yuekao.entity.NetSong;
import com.bawei.yuekao.entity.Song;
import com.bawei.yuekao.entity.SongList;
import com.bawei.yuekao.service.DownloadService;
import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**

 */
public class NetMusicFragment extends Fragment {

//    根据歌手搜索歌曲名称
//    https://autumnfish.cn/search?keywords=邓紫棋
//
//    根据歌曲id获得歌曲地址
//    https://autumnfish.cn/song/url?id=36024806

    private String url_list = "https://autumnfish.cn/search?keywords=法老";
    private String url_song = "https://autumnfish.cn/song/url?id=";
    private ListView listView;
    private List<Song> list = new ArrayList<>();
    private SongAdapter songAdapter;
    private DownloadRecevier downloadRecevier;



    public NetMusicFragment() {

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_net_music, container, false);
        listView = view.findViewById(R.id.lv);
        new MyTask().execute();
        //点击下载服务
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                initService(position);
            }
        });
        initRecevicer();
        return view;
    }
    //注册广播
    private void initRecevicer() {
        downloadRecevier = new DownloadRecevier();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.music.download");
        getActivity().registerReceiver(downloadRecevier,intentFilter);

    }
    //解除注册
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(downloadRecevier);
    }
    //启动服务
    private void initService(int position) {
        Intent intent = new Intent(getActivity(), DownloadService.class);
        Bundle bundle = new Bundle();
        bundle.putString("url",list.get(position).getData());
        bundle.putString("name",list.get(position).getName());
        intent.putExtras(bundle);
        getActivity().startService(intent);//不需要手动停止
    }

    class DownloadRecevier extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.music.download".equals(intent.getAction())){
                Toast.makeText(context, "下载完成", Toast.LENGTH_SHORT).show();
            }
        }
    }



    class MyTask extends AsyncTask<String,String,String>{

        @Override
        protected String doInBackground(String... strings) {
            StringBuffer stringBuffer = new StringBuffer();
            try {
                {
                    URL url = new URL(url_list);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.connect();

                    InputStream inputStream = httpURLConnection.getInputStream();
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(bytes)) != -1) {
                        stringBuffer.append(new String(bytes, 0, len));
                    }
                }
                SongList songList = new Gson().fromJson(stringBuffer.toString(), SongList.class);
                List<SongList.ResultBean.SongsBean> songs = songList.getResult().getSongs();
                for (SongList.ResultBean.SongsBean song : songs) {
                    String name = song.getName();
                    String album = song.getArtists().get(0).getImg1v1Url();
                    int id = song.getId();
                    {
                        URL url = new URL(url_song+id);
                        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                        httpURLConnection.connect();
                        StringBuffer stringBuffer2 = new StringBuffer();
                        InputStream inputStream = httpURLConnection.getInputStream();
                        byte[] bytes = new byte[1024];
                        int len = 0;
                        while ((len = inputStream.read(bytes)) != -1) {
                            stringBuffer2.append(new String(bytes, 0, len));
                        }
                        NetSong netSong = new Gson().fromJson(stringBuffer2.toString(), NetSong.class);
                        String url1 = netSong.getData().get(0).getUrl();
                        list.add(new Song(name,"邓紫棋",url1,album));


                    }


                }


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            songAdapter = new SongAdapter(list,getActivity());
            listView.setAdapter(songAdapter);
        }
    }


}
